<?php
/**
* The gateway to managing events.
*
* Copyright (c) 2009 James Gauld <james@jamesgauld.net>
* This file is part of Scribble.
* @license http://www.scribblecms.co.uk/license.txt
*
* @package Scribble
*/
abstract class ScribbleEventManager {

	/**
	* All registered listeners, indexed by event name.
	*
	* @var array
	*/
	private static $listeners = array();

	/**
	* Add a listener to the specified event. Returns an object containing some
	* basic info about the listener.
	*
	* The listener can be any one of:
	*		A global function name, eg. "myFunction"
	*		A class instance method, eg. array($instance, "methodName")
	*		A static class method, eg. array("className", "methodName")
	*		A lambda function, eg. function() { ... }
	*
	* @param string Event name
	* @param mixed The listener
	* @return \StdClass
	*/
	public static function addEventListener($eventName, $listener) {
		$info = new StdClass();
		$info->id = uniqid(rand());
		self::$listeners[$eventName][$info->id] = $listener;
		return $info;
	}

	/**
	* Execute all listeners on the specified event.
	*
	* Note that any additional arguments you pass to this method will be passed as
	* values and NOT as references.
	*
	* @param ScribbleEvent Event to dispatch
	* @params mixed You can pass any number of arguments that will be passed to
	*		the listeners
	* @return void
	*/
	public static function dispatchEvent($event) {
		if(!empty(self::$listeners[$event->name])) {
			$args = func_get_args();
			foreach(self::$listeners[$event->name] as $l) {
				call_user_func_array($l, $args);
			}
		}
	}

	/**
	* Remove the listener identified by the given ID.
	*
	* @param string Event name
	* @param string Listener ID (as returned by addEventListener())
	* @result void
	*/
	public static function removeEventListener($eventName, $listenerId) {
		if(isset($this->listeners[$eventName][$listenerId])) {
			unset($this->listeners[$eventName][$listenerId]);
		}
	}
}
?>